package com.xxkj.drugtraceability.net
import android.content.Context
import com.xxkj.drugtraceability.App.Companion.CONTEXT
import com.xxkj.drugtraceability.utils.NetWorkUtils
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import java.io.File
import retrofit2.Retrofit
import java.lang.Exception
import java.lang.reflect.Field
import kotlin.jvm.Throws


object WanRetrofitClient: BaseRetrofitClient() {
    val service by lazy { getService(WanService::class.java, WanService.BASE_URL) }
    override fun handleBuilder(builder: OkHttpClient.Builder) {
        val httpCacheDirectory = File(CONTEXT.cacheDir, "responses")
        val cacheSize = 10 * 1024 * 1024L // 10 MiB
        val cache = Cache(httpCacheDirectory, cacheSize)
        builder.cache(cache)
            .addInterceptor { chain ->
                var request = chain.request()
                if (!NetWorkUtils.isNetworkAvailable(CONTEXT)) {
                    request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build()
                }
                val response = chain.proceed(request)
                if (!NetWorkUtils.isNetworkAvailable(CONTEXT)) {
                    val maxAge = 60 * 60
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, max-age=$maxAge")
                        .header("Connection", "close")
                        .build()
                } else {
                    val maxStale = 60 * 60 * 24 * 28 // tolerate 4-weeks stale
                    response.newBuilder()
                        .removeHeader("Pragma")
                        .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
                        .header("Connection", "close")

                    .build()
                }
                response
            }
    }

    @Throws(Exception::class)
    fun baseUrl(retrofit: Retrofit, baseUrl: String) {
        val httpUrl = baseUrl.toHttpUrlOrNull()
        var field: Field = retrofit.javaClass.getDeclaredField("baseUrl")
        field.isAccessible = true
        field.set(retrofit, httpUrl)
        field = retrofit.javaClass.getDeclaredField("serviceMethodCache")
        field.isAccessible = true
        val serviceMethodCache = field.get(retrofit) as MutableMap<*, *>
        serviceMethodCache.clear()
    }
}